package com.ttdevs.ttrss.ui;

import java.text.SimpleDateFormat;
import java.util.LinkedList;
import java.util.List;

import org.mcsoxford.rss.RSSItem;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ttdevs.ttrss.R;
import com.ttdevs.ttrss.bean.Article;
import com.ttdevs.ttrss.net.IConnection.OnResponseListener;
import com.ttdevs.ttrss.net.URLConn;

public class CustomFragment extends Fragment implements OnItemClickListener, OnRefreshListener2<ListView> {

	private static final int PAGESIZE = 20;

	private static String mLink;
	private CustomActivity mActivity;
	// private IDBManager dbm;
	private PullToRefreshListView mPullRefreshListView;
	private ArticleListAdapter adapter;
	private ListView mListView;
	private List<Article> mList;

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (mPullRefreshListView.isRefreshing()) {
				mPullRefreshListView.onRefreshComplete();
			}
			adapter.setArticleList(mList);
			adapter.notifyDataSetChanged();
		};
	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = (CustomActivity) activity;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// dbm = AppInit.getDBManager();

		mList = new LinkedList<Article>();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.content_custom, container, false);
		mPullRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		mPullRefreshListView.setOnRefreshListener(this);

		mListView = mPullRefreshListView.getRefreshableView();
		mListView.setDivider(getResources().getDrawable(R.drawable.divider));
		System.out.println(">>>>>onCreateView" + mList.toString());
		adapter = new ArticleListAdapter(getActivity(), mList);
		mListView.setAdapter(adapter);
		mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mListView.setOnItemClickListener(this);

		return view;
	}

	public void setLink(String link) {
		mLink = link;

		// mList = dbm.queryArticle(link, Integer.MAX_VALUE, PAGESIZE);
		// mList.addAll(dbm.queryArticle(link, Integer.MAX_VALUE, PAGESIZE));
		// if (mList.size() > 0) {
		// System.out.println(">>>>>setLink" + mList.toString());
		// adapter.setArticleList(mList);
		// adapter.notifyDataSetChanged();
		// } else {
		// onPullDownToRefresh(null);
		// }
		onPullDownToRefresh(null);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		mActivity.setProgressBar(true);

		new URLConn().sendRequest(mLink, new OnResponseListener() {

			@Override
			public void oResponse(boolean isSuccess, List<RSSItem> lists) {
				if (isSuccess) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EEE", java.util.Locale.ENGLISH);

					mList.clear();
					for (RSSItem item : lists) {
						// 标题、连接地址、标题简介、时间是一个Rss源项最基本的组成部分
						System.out.println("标题：" + item.getTitle());
						System.out.println("连接地址：" + item.getLink());
						System.out.println("标题简介：" + item.getDescription());
						System.out.println("发布时间：" + item.getPubDate());
						System.out.println("内容：" + item.getContent());
						// System.out.println("内容：" +
						// item.getCategories().toString());

						// 以下是Rss源可先的几个部分
						// System.out.println("标题的作者：" + item.getAuthor());

						Article art = new Article();
						art.setIcon("");
						art.setTitle(item.getTitle());
						art.setDescription(item.getDescription());
						art.setPubDate(sdf.format(item.getPubDate()));
						art.setGuid(item.getLink().toString());
						art.setLink(item.getLink().toString());
						art.setSource(mLink);
						art.setAuthor("");
						art.setMark(false);
						art.setRead(false);
						art.setCreateTime(System.currentTimeMillis());
						mList.add(art);
					}
					// dbm.insertArticles(articles);
				}
				mActivity.setProgressBar(false);
				handler.sendEmptyMessage(0);
			}
		});
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		String url = ((TextView)view.findViewById(R.id.tvLink)).getText().toString();
		if(url == null || "".equals(url)){
			Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
		}else{
			Intent intent = new Intent(getActivity(), ArticleDetailActivity.class);
			intent.putExtra(ArticleDetailActivity.KEY_URL, url);
			startActivity(intent);
		}
	}
}
